import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Input,
  Button,
} from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Storage from '../../utils/localstore';
import { profileItemData } from './utils';

import './index.less';

const FormItem = Form.Item;

@connect(state => ({
  profile: state.organProfile,
}))
@Form.create()
export default class OrganProfile extends Component {
  state = {
    initLoad: true,
  }

  componentDidMount() {
    const uid = Storage.get('uid');

    const { dispatch } = this.props;
    dispatch({
      type: 'organProfile/fetchBasic',
      payload: {
        uid,
      },
    });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.profile.status === 'ok' && this.state.initLoad) {
      const profileData = nextProps.profile.form;
      this.setState({
        initLoad: false,
      });
      this.props.form.setFieldsValue(profileData);
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const uid = Storage.get('uid');
    this.props.form.validateFields({ force: true },
      (err, values) => {
        if (!err) {
          this.props.dispatch({
            type: 'organProfile/submitProfile',
            payload: {
              uid,
              ...values,
            },
          });
        }
      }
    );
  }

  // 根据表单数据生成输入框
  formGenerator = (options, key) => {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    return (
      <FormItem
        {...formItemLayout}
        label={options.label}
        hasFeedback
        key={key}
      >
        {getFieldDecorator(options.name, {
          rules: options.rules,
        })(
          <Input disabled={options.name === 'contact_email'} />
          )}
      </FormItem>
    );
  }

  render() {
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 14,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    const forms = profileItemData.map(this.formGenerator);

    return (
      <PageHeaderLayout title="基础详情页">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit}>
            {forms}
            <FormItem {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit" size="large">保存</Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}

